# -*- coding: utf-8 -*-

#    Copyright (C) 2005-2012 by Promotux
#                        di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of Promogest. http://www.promogest.me

#    Promogest is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    Promogest is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with Promogest.  If not, see <http://www.gnu.org/licenses/>.

from promogest.lib.page import Page
from promogest.dao.AnagraficaSecondaria import AnagraficaSecondaria_
from promogest.modules.RuoliAzioni.dao.Role import Role
from promogest.dao.PersonaGiuridica import\
    PersonaGiuridica_ as PersonaGiuridica
from promogest.dao.Cliente import Cliente
from promogest.dao.PersonaGiuridicaPersonaGiuridica import \
    PersonaGiuridicaPersonaGiuridica
from promogest.dao.TestataDocumento import TestataDocumento
from promogest.lib.webutils import *
from promogest.modules.InfoPeso.dao.TestataInfoPeso import TestataInfoPeso


@expose('/main')
def mainpage(req, subdomain=None):
    """
    Main
    """
    # PASSARE LE ATTIVITA' se azienda è giusto peso
    #prome = Promemoria().select(batchSize=None)
    id_pg = None
    pg = None
    tip = None
    if getUserFromId(req):
        pg = PersonaGiuridica().select(idUser=getUserFromId(req).id)
        if pg:
            id_pg = pg[0].id
    if id_pg:
        tip = TestataInfoPeso().select(idCliente=id_pg)
        if req.form.get("privacy") == "1" and tip:
            tip[0].privacy = True
            tip[0].persist()
    pgs = []
    if id_pg:
        pgg = PersonaGiuridicaPersonaGiuridica()\
            .select(idPersonaGiuridicaAbbinata=id_pg)
        for p in pgg:
            pgs.append(AnagraficaSecondaria_()\
                .getRecord(id=p.id_persona_giuridica))
    else:
        role = Role().select(name="ATTIVITA")
        if role:
            idrole = role[0].id
            pgs = AnagraficaSecondaria_().select(idRole=idrole, batchSize=None,
                orderBy="ragione_sociale")
    odc = []
    if pg:
        #daoCliente = pg[0]
        daoCliente = Cliente().getRecord(id=pg[0].id)
        if daoCliente and "zanotti" in daoCliente.ragione_sociale.lower():
            #odc = TestataDocumento().select(idCliente = id_pg, batchSize=None)
            odc = []
        else:
            odc = ["NON ANCORA"]
    else:
        daoCliente = None
    co = req.args.get("co")
    ec = req.args.get("ec")
    if not getUserFromId(req):
        redirectUrl="/"
        return Page(req).redirect(redirectUrl)
    else:
        boh = getUserFromId(req).email_confirmed
        filet = "mainpage"
    pageData = {'file': filet,
                "show_spalla": False,
                "pg": pg,
                "daoCliente": daoCliente,
                "tip": tip,
                "odc": odc,
                "co":co,
                "ec":ec,
                "pgsecondaria": pgs,
                "emailDaConfermare": boh
                }


    def pickle_meta():
        from pickle import dump
        if not os.path.exists(os.path.join(Environment.CONFIGPATH, Environment.meta_pickle)):
            with open(os.path.join(Environment.CONFIGPATH, Environment.meta_pickle), 'wb') as f:
                dump(Environment.meta, f)
    pickle_meta()
    return Page(req).render(pageData)
